package com.gr.dmbackend.service.Impl.dormaddmin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.dmbackend.mapper.*;
import com.gr.dmbackend.model.*;
import com.gr.dmbackend.service.dormaddmin.AddEventService;
import com.gr.dmbackend.utils.GetUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AddEventServiceImpl implements AddEventService {

    @Autowired
    private EventMapper eventMapper;

    @Autowired
    private DormaddminMapper dormaddminMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private StudentEventMapper studentEventMapper;

    @Override
    public JSONObject addEvent(Map<String, String> data) {
        JSONObject resp = new JSONObject();

        String title = data.get("title");
        String htmlContent = data.get("htmlContent");

        if (title.isEmpty()) {
            resp.put("error_message", "标题不能为空");
            return resp;
        }
        if (htmlContent.isEmpty()) {
            resp.put("error_message", "文章内容不能为空");
            return resp;
        }
        if (title.length() > 40) {
            resp.put("error_message", "标题长度超出限制");
            return resp;
        }

        Date now = new Date();
        QueryWrapper<Dormaddmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_id", GetUserUtil.getCurrentUser().getUsername());
        Dormaddmin dormaddmin = dormaddminMapper.selectOne(queryWrapper);
        if (dormaddmin == null) {
            resp.put("error_message", "当前用户不存在");
            return resp;
        }
        Event event = new Event();
        event.setWorkId(GetUserUtil.getCurrentUser().getUsername());
        event.setTitle(title);
        event.setHtmlContent(htmlContent);
        event.setCreatetime(now);
        event.setAuthor(dormaddmin.getName());
        eventMapper.insert(event);

        QueryWrapper<Building> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("addmin_id", dormaddmin.getWorkId());
        List<Building> buildings = buildingMapper.selectList(queryWrapper1);
        QueryWrapper<Student> queryWrapper2 = new QueryWrapper<>();
        for (Building building: buildings) {
            queryWrapper2.eq("building", building.getName());
        }
        List<Student> students = studentMapper.selectList(queryWrapper2);
        for (Student student: students) {
            StudentEvent studentEvent = new StudentEvent();
            studentEvent.setStudentId(student.getStudentId());
            studentEvent.setEventId(event.getId());
            studentEventMapper.insert(studentEvent);
        }
        resp.put("error_message", "success");

        return resp;
    }
}
